package com.example.exceptions;

import com.example.result.MSG;
import com.example.result.Result;
import com.example.result.ResultData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 异常处理器
 * @Author: chen
 * @CreateTime: 2022-08-16
 * @Version: 1.0
 */
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public Result returnCustomException(CustomException e) {
        e.printStackTrace();
        return ResultData.error(e.getResponseEnum());
    }

    @ExceptionHandler(ParamsException.class)
    @ResponseBody
    public Result returnCustomException(ParamsException e) {
        return ResultData.error(e.getResponseEnum(),e.getData());
    }

    // 除零异常
    @ExceptionHandler(ArithmeticException.class)
    @ResponseBody
    public Result arithmeticException(ArithmeticException e) {
        e.printStackTrace();
        return ResultData.error(MSG.SYSTEM_ARITHMETIC_BY_ZERO);
    }

    // 空指针
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public Result nullException(NullPointerException e) {
        e.printStackTrace();
        return ResultData.error(MSG.SYSTEM_NULL_POINTER);
    }

    // 数组越界
    @ExceptionHandler(ArrayIndexOutOfBoundsException.class)
    @ResponseBody
    public Result arrayIndexException(ArrayIndexOutOfBoundsException e) {
        e.printStackTrace();
        return ResultData.error(MSG.SYSTEM_INDEX_OUT_OF_BOUNDS);
    }

    // 未知异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result unknown(Exception e) {
        e.printStackTrace();
        return ResultData.error(MSG.SYSTEM_OPERATION_ERROR);
    }

}
